package com.youcash.ZyWallet_spring.service.impl;

import com.youcash.ZyWallet_spring.dao.NewsListMapper;
import com.youcash.ZyWallet_spring.entity.NewsList;
import com.youcash.ZyWallet_spring.service.NewsListService;
import com.youcash.ZyWallet_spring.vo.ResStatus;
import com.youcash.ZyWallet_spring.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class NewsListServiceImpl implements NewsListService {

    @Autowired
    private NewsListMapper newsListMapper;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    @Override
    public ResultVO listNews() {
        Example example = new Example(NewsList.class);
        List<NewsList> newsList = newsListMapper.selectByExample(example);
        if (newsList.size() == 0) {
            return new ResultVO(ResStatus.NO, "查询失败！", null);
        } else {
            return new ResultVO(ResStatus.OK, "查询成功！", newsList);
        }
    }

    @Override
    public ResultVO listNewsByStatus(int status) {
        Example example = new Example(NewsList.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status", status);
        List<NewsList> newsList = newsListMapper.selectByExample(example);
        if (newsList.size() == 0) {
            return new ResultVO(ResStatus.NO, "查询失败！", null);
        } else {
            return new ResultVO(ResStatus.OK, "查询成功！", newsList);
        }
    }

    @Override
    public ResultVO updateStatus(int id, int status) {
        int i = newsListMapper.updateStatusById(id, status);
        if (i > 0) {
            return new ResultVO(ResStatus.OK, "更新成功", null);
        } else {
            return new ResultVO(ResStatus.NO, "更新失败", null);
        }
    }

    @Override
    public ResultVO addNews(NewsList newsList) {
        newsList.setUpdatetime(sdf.format(new Date()));
        newsList.setCreatetime(sdf.format(new Date()));
        int i = newsListMapper.insert(newsList);
        if (i > 0) {
            return new ResultVO(ResStatus.OK, "添加成功", null);
        } else {
            return new ResultVO(ResStatus.NO, "添加失败", null);
        }
    }

    @Override
    public ResultVO updateInfo(int id, String title, String article, String updatetime) {
        updatetime = sdf.format(new Date());
        int i = newsListMapper.updateInfoById(id, title, article, updatetime);
        if (i > 0) {
            return new ResultVO(ResStatus.OK,"更新成功",null);
        } else {
            return new ResultVO(ResStatus.NO,"更新失败",null);
        }
    }
}
